// Package middleware 提供基础 CORS 中间件，便于本地前端联调
package middleware

import (
	"net/http"
)

// CORS 返回允许常见方法与头的跨域中间件
func CORS(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PATCH,DELETE,OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type,X-API-Key,Idempotency-Key")
		w.Header().Set("Access-Control-Expose-Headers", "Idempotency-Key,Idempotency-Generated")
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusNoContent)
			return
		}
		next.ServeHTTP(w, r)
	})
}
